package org.hospital.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hospital.entity.Clinic;
import org.hospital.entity.Department;
import org.hospital.entity.Employee;
import org.hospital.entity.Log;
import org.hospital.entity.Position;
import org.hospital.service.ClinicService;
import org.hospital.service.DepartmentService;
import org.hospital.service.LogService;
import org.hospital.service.PermissionService;
import org.hospital.service.UserService;
import org.hospital.util.Constant;
import org.hospital.util.DateUtil;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "clinicController")
@SessionAttributes(value = "employee", types = Employee.class)
public class ClinicController {
	@Autowired
	private UserService uService;
	@Autowired
	private PermissionService pmService;
	@Autowired
	private LogService lService;
	@Autowired
	private ClinicService cService;
	@Autowired
	private DepartmentService dpmService;

	@ResponseBody
	@RequestMapping(value = "/getAllClinic", produces = "text/json;charset=utf-8")
	public String getAllClinic(HttpSession session) {
		// 检测用户权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		JSONArray resultJA = cService.getAll();
		if (resultJA == null || resultJA.size() == 0) {
			return StringUtil.setResult(414, "信息为空", "");
		}
		return StringUtil.setResult(200, "操作成功", resultJA);
	}

	/**
	 * 
	 * @param req
	 *            {clinicId}
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getClinicById", produces = "text/json;charset=utf-8")
	public String getClinicById(WebRequest req) {

		try {
			// 获取参数
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			// 查询数据库
			Clinic clinic = cService.getByid(clinicId);
			if (clinic == null) {
				return StringUtil.setResult(414, "信息为空", "");
			}
			Employee creator = uService.getEmployeeById(clinic.getCreatorId());
			// 格式化数据
			JSONObject resultJO = new JSONObject();
			resultJO.put("clinicId", clinic.getClinicId());
			resultJO.put("clinicName", clinic.getName());
			resultJO.put("creatorId", clinic.getCreatorId());
			resultJO.put("creatorName", creator.getName());
			resultJO.put("creatorCode", creator.getEmployeeCode());
			resultJO.put("createTime", sdf.format(clinic.getCreateTime()));
			if (clinic.getAddress() == null) {
				resultJO.put("address", "null");
			} else {
				resultJO.put("address", clinic.getAddress());
			}
			if (clinic.getPhone() == null) {
				resultJO.put("phone", "null");
			} else {
				resultJO.put("phone", clinic.getPhone());
			}
			return StringUtil.setResult(200, "操作成功", resultJO);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}

	}

	/**
	 * 获取门诊下的所有部门
	 * 
	 * @param req
	 *            {clinicId}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getClinicAllDepartment", produces = "text/json;charset=utf-8")
	public String getClinicAllDepartment(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}

		try {
			// 获取数据
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			JSONArray resultJA = dpmService.getClinicAllDepartment(clinicId);

			if (null == resultJA || resultJA.size() == 0) {
				return StringUtil.setResult(414, "门诊下部门信息为空", "");
			}

			return StringUtil.setResult(200, "操作成功", resultJA);

		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getAllDepartment", produces = "text/json;charset=utf-8")
	public String getAllDepartment(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		try {
			JSONArray resultJA = dpmService.getAllDepartment();
			if (null == resultJA || resultJA.size() == 0) {
				return StringUtil.setResult(414, "部门信息为空", "");
			}
			return StringUtil.setResult(200, "操作成功", resultJA);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}
	}

	/**
	 * 创建门诊 只有管理员能够创建
	 * 
	 * @param req
	 *            {employeeId(门诊负责人Id),name,?phone,?address}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createClinic", produces = "text/json;charset=utf-8")
	public String createClinic(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_CLINIC.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}
		try {
			// 获取数据
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			String name = req.getParameter("name");
			String address = req.getParameter("address");
			String phone = req.getParameter("phone");
			if (name == null || name == "") {
				return StringUtil.setResult(403, "缺少name参数", "");
			}

			// 验证employeeId 有效性
			// 门诊负责人
			Employee principal = uService.getEmployeeById(employeeId);
			if (principal == null) {
				return StringUtil.setResult(403, "不存在此employeeId", "");
			}
			Position position = pmService.getPositionByid(principal.getPositionId());
			if (position.getRank() < 3) {
				return StringUtil.setResult(403, "employeeId职位权限不足", "");
			}

			Clinic clinic = new Clinic();
			clinic.setEmployeeId(employeeId);
			clinic.setCreatorId(operator.getEmployeeId());
			clinic.setName(name);
			if (address != null) {
				clinic.setAddress(address);
			} else {
				clinic.setAddress("null");
			}
			if (phone != null) {
				clinic.setPhone(phone);
			} else {
				clinic.setPhone("null");
			}
			clinic.setCreateTime(new Timestamp(DateUtil.getNowLong()));

			// 插入数据库
			clinic = cService.addEntity(clinic);
			if (clinic == null) {
				return StringUtil.setResult(501, "数据库插入错误", "");
			}

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_CLINIC.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(clinic));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", clinic);

		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}
	}

	/**
	 * 创建部门 只有管理员能够创建
	 * 
	 * @param req
	 *            {clinicId,employeeId(科室负责人Id),name,?phone}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createDepartment", produces = "text/json;charset=utf-8")
	public String createDepartment(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_DEPARTMENT.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		try {
			// 获取数据
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			String name = req.getParameter("name");
			String phone = req.getParameter("phone");

			// 检验合法性
			Clinic clinic = cService.getByid(clinicId);
			if (null == clinic) {
				return StringUtil.setResult(403, "不存在此clinicId", "");
			}
			Employee principle = uService.getEmployeeById(employeeId);
			if (null == principle) {
				return StringUtil.setResult(403, "不存在此employeeId", "");
			}
			Position position = pmService.getPositionByid(principle.getPositionId());
			if (position.getRank() < 2) {
				return StringUtil.setResult(403, "employeeId权限不足", "");
			}
			if (name == null) {
				return StringUtil.setResult(403, "缺少name字段", "");
			}

			// 准备数据
			Department dpm = new Department();
			dpm.setClinicId(clinicId);
			dpm.setEmployeeId(employeeId);
			dpm.setName(name);
			if (phone == null) {
				dpm.setPhone("null");
			} else {
				dpm.setPhone(phone);
			}
			dpm.setCreatorId(operator.getEmployeeId());
			dpm.setCreateTime(new Timestamp(DateUtil.getNowLong()));

			// 插入数据库
			dpm = dpmService.addEntity(dpm);
			if (dpm == null) {
				return StringUtil.setResult(501, "数据库插入错误", "");
			}

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_DEPARTMENT.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(dpm));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", dpm);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 修改门诊基本信息 权限： 3、4:是该门诊负责人;5:可以修改;具有创建权限
	 * 
	 * @param req
	 *            {clinicId,employeeId,name,?address,?phone}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/alterClinic", produces = "text/json;charset=utf-8")
	public String alterClinic(WebRequest req, HttpSession session) {
		try {
			// 获取数据
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			String name = req.getParameter("name");
			String address = req.getParameter("address");
			String phone = req.getParameter("phone");

			// 验证合法性
			if (name == null) {
				StringUtil.setResult(403, "缺少name参数", "");
			}
			Employee principal = uService.getEmployeeById(employeeId);
			if (principal == null) {
				return StringUtil.setResult(403, "不存在此employeeId", "");
			}
			Position position = pmService.getPositionByid(principal.getPositionId());
			if (position.getRank() < 3) {
				return StringUtil.setResult(403, "employeeId职位权限不足", "");
			}
			Clinic clinic = cService.getByid(clinicId);
			if (null == clinic) {
				return StringUtil.setResult(403, "不存在此clinicId", "");
			}

			// 验证权限
			Employee operator = (Employee) session.getAttribute("employee");
			if (operator == null) {
				return StringUtil.setResult(405, "请重新登陆", "");
			}
			if (pmService.isPermisionEnough(operator.getPositionId(),
					Constant.CREATE_CLINIC.getName(), 5)) {
				// 具有创建门诊权限的管理员
				clinic.setEmployeeId(employeeId);
				clinic.setName(name);
				if (address != null) {
					clinic.setAddress(address);
				}
				if (phone != null) {
					clinic.setPhone(phone);
				}
				clinic = cService.addEntity(clinic);
				if (clinic == null) {
					return StringUtil.setResult(501, "数据库插入错误", "");
				}

			} else if (clinic.getEmployeeId() == operator.getEmployeeId()) {
				// 门诊负责人
				clinic.setName(name);
				if (address != null) {
					clinic.setAddress(address);
				}
				if (phone != null) {
					clinic.setPhone(phone);
				}
				clinic = cService.addEntity(clinic);
				if (clinic == null) {
					return StringUtil.setResult(501, "数据库插入错误", "");
				}
			} else {
				return StringUtil.setResult(402, "权限不足", "");
			}

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_CLINIC.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(clinic));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", clinic);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}

	}

	/**
	 * 修改科室 权限:2、3、4:是该科室负责人;3、4:是该门诊负责人;5：可以修改;具有创建权限
	 * 
	 * @param req
	 *            {departmentId,clinicId,employeeId,name,?phone}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/alterDepartment", produces = "text/json;charset=utf-8")
	public String alterDepartment(WebRequest req, HttpSession session) {
		try {
			// 获取数据
			int departmentId = Integer.parseInt(req.getParameter("departmentId"), 10);
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			String name = req.getParameter("name");
			String phone = req.getParameter("phone");

			// 验证合法性
			if (name == null) {
				StringUtil.setResult(403, "缺少name参数", "");
			}
			Employee principal = uService.getEmployeeById(employeeId);
			if (principal == null) {
				return StringUtil.setResult(403, "不存在此employeeId", "");
			}
			Position position = pmService.getPositionByid(principal.getPositionId());
			if (position.getRank() < 2) {
				return StringUtil.setResult(403, "employeeId职位权限不足", "");
			}
			Clinic clinic = cService.getByid(clinicId);
			if (null == clinic) {
				return StringUtil.setResult(403, "不存在此clinicId", "");
			}
			Department dpm = dpmService.getByid(departmentId);
			if (null == dpm) {
				return StringUtil.setResult(403, "不存在此departmentId", "");
			}

			// 验证权限
			Employee operator = (Employee) session.getAttribute("employee");
			if (operator == null) {
				return StringUtil.setResult(405, "请重新登陆", "");
			}
			if (pmService.isPermisionEnough(operator.getPositionId(),
					Constant.CREATE_DEPARTMENT.getName(), 5)) {
				// 具有创建门诊权限的管理员
				dpm.setEmployeeId(employeeId);
				dpm.setName(name);
				if (phone != null) {
					dpm.setPhone(phone);
				}
				dpm = dpmService.addEntity(dpm);
				if (dpm == null) {
					return StringUtil.setResult(501, "数据库插入错误", "");
				}

			} else if (clinic.getEmployeeId() == operator.getEmployeeId()) {
				// 门诊负责人
				dpm.setName(name);
				dpm.setEmployeeId(employeeId);
				if (phone != null) {
					clinic.setPhone(phone);
				}
				dpm = dpmService.addEntity(dpm);
				if (dpm == null) {
					return StringUtil.setResult(501, "数据库插入错误", "");
				}
			} else if (dpm.getEmployeeId() == operator.getEmployeeId()) {
				// 科室负责人
				dpm.setName(name);
				if (phone != null) {
					clinic.setPhone(phone);
				}
				dpm = dpmService.addEntity(dpm);
				if (dpm == null) {
					return StringUtil.setResult(501, "数据库插入错误", "");
				}
			} else {
				System.out.println("alterDepartment.dpm : " + dpm.getEmployeeId());
				System.out.println("alterDepartment operator : " + operator.getEmployeeId());
				return StringUtil.setResult(402, "权限不足", "");
			}

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_CLINIC.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(clinic));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", dpm);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
}
